﻿using Entity;
using IService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.IO;
using System.Text.Json;

namespace XingWeiDaWMSProject.Controllers
{
    public class NumberingRuleController : BaseController
    {
        private readonly INumberingRuleService _numberingRuleService;
        private readonly ITargetFormService _targetFormService;

        public NumberingRuleController(INumberingRuleService numberingRuleService, ITargetFormService targetFormService)
        {
            _numberingRuleService = numberingRuleService ?? throw new ArgumentNullException(nameof(numberingRuleService));
            _targetFormService = targetFormService ?? throw new ArgumentNullException(nameof(targetFormService));
        }

        /// <summary>
        /// 获取当前登录用户
        /// </summary>
        private string GetCurrentUserName()
        {
            try
            {
                // 从Session获取
                if (HttpContext.Session.Keys.Contains("LoginUserName"))
                {
                    var sessionUserName = HttpContext.Session.GetString("LoginUserName");
                    if (!string.IsNullOrEmpty(sessionUserName))
                    {
                        Console.WriteLine($"【用户识别】从Session获取到用户名：{sessionUserName}");
                        return sessionUserName;
                    }
                }

                // 从Claim获取
                var possibleClaims = new List<string>
                {
                    ClaimTypes.Name, ClaimTypes.NameIdentifier,
                    "username", "userName", "LoginName", "Account"
                };
                foreach (var claimType in possibleClaims)
                {
                    var value = User.FindFirstValue(claimType);
                    if (!string.IsNullOrEmpty(value))
                    {
                        Console.WriteLine($"【用户识别】从Claim '{claimType}' 获取到用户：{value}");
                        return value;
                    }
                }

                // 从Identity获取
                if (User.Identity.IsAuthenticated && !string.IsNullOrEmpty(User.Identity.Name))
                {
                    Console.WriteLine($"【用户识别】从Identity获取到用户：{User.Identity.Name}");
                    return User.Identity.Name;
                }

                // 兜底方案
                return "system";
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【用户识别】异常：{ex.Message}");
                return "system";
            }
        }

        /// <summary>
        /// 生成业务单据号 - 修复版本
        /// </summary>
        [HttpPost]
        public IActionResult GenerateBusinessNumber([FromBody] GenerateNumberRequest request)
        {
            try
            {
                Console.WriteLine($"【GenerateBusinessNumber】接收规则ID：{request.rule_id}");

                if (request.rule_id <= 0)
                {
                    Console.WriteLine($"【GenerateBusinessNumber】错误：规则ID必须大于0");
                    return Json(new { success = false, message = "规则ID必须大于0" });
                }

                // 关键修复：直接根据rule_id生成编号，不再查询target_form
                Console.WriteLine($"【GenerateBusinessNumber】直接使用rule_id={request.rule_id}生成编号");

                var currentUser = GetCurrentUserName();
                string businessNumber = _numberingRuleService.GenerateBusinessNumber(request.rule_id, currentUser);

                Console.WriteLine($"【GenerateBusinessNumber】生成编号成功：{businessNumber}");
                return Json(new { success = true, businessNumber = businessNumber });
            }
            catch (KeyNotFoundException ex)
            {
                Console.WriteLine($"【GenerateBusinessNumber】错误：{ex.Message}");
                return Json(new { success = false, message = ex.Message });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【GenerateBusinessNumber】异常：{ex.Message}\n{ex.StackTrace}");
                return Json(new { success = false, message = $"生成业务单据号失败：{ex.Message}" });
            }
        }

        // 新增：定义接收参数的模型（放在Controller内部或单独的Models文件夹）
        public class GenerateNumberRequest
        {
            public int rule_id { get; set; } // 与前端传递的参数名保持一致
        }

        /// <summary>
        /// 根据规则生成日期部分
        /// </summary>
        private string GenerateDatePart(NumberingRule rule)
        {
            if (string.IsNullOrEmpty(rule.time_rule))
                return DateTime.Now.ToString("yyyyMMdd"); // 默认格式

            var date = DateTime.Now;
            var datePart = new System.Text.StringBuilder();

            // 严格按照time_rule中的格式生成（支持YYYY、MM、DD、HH、mm、ss）
            if (rule.time_rule.Contains("YYYY")) datePart.Append(date.ToString("yyyy"));
            if (rule.time_rule.Contains("MM")) datePart.Append(date.ToString("MM"));
            if (rule.time_rule.Contains("DD")) datePart.Append(date.ToString("dd"));
            if (rule.time_rule.Contains("HH")) datePart.Append(date.ToString("HH"));
            if (rule.time_rule.Contains("mm")) datePart.Append(date.ToString("mm"));
            if (rule.time_rule.Contains("ss")) datePart.Append(date.ToString("ss"));

            return datePart.ToString();
        }

        /// <summary>
        /// 显示编号规则列表页
        /// </summary>
        public IActionResult Index()
        {
            try
            {
                Console.WriteLine($"【Index】用户 {GetCurrentUserName()} 访问编号规则列表页");

                // 首次加载时获取第一页数据
                var queryParams = new NumberingRuleQueryParams
                {
                    PageIndex = 1,
                    PageSize = 10
                };
                var result = _numberingRuleService.GetByConditions(queryParams);
                var rules = result?.Data ?? new List<NumberingRule>();

                foreach (var rule in rules)
                {
                    rule.serial_number = rule.serial_number > 0 ? rule.serial_number : 0;
                    rule.step = rule.step > 0 ? rule.step : 1;
                    rule.time_rule = rule.time_rule ?? string.Empty;
                    rule.number_production_rule = rule.number_production_rule ?? string.Empty;
                }

                var targetForms = _targetFormService.GetAll() ?? new List<TargetForm>();
                List<SelectListItem> targetFormItems = new List<SelectListItem>();
                foreach (var form in targetForms)
                {
                    targetFormItems.Add(new SelectListItem
                    {
                        Value = form.target_id.ToString(),
                        Text = form.target_form
                    });
                }
                ViewBag.TargetForms = targetFormItems;

                return ReturnViewOrPartial(rules);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【Index】异常：{ex.Message}\n{ex.StackTrace}");
                return View("Error", new { Message = $"加载列表失败: {ex.Message}" });
            }
        }

        [HttpPost]
        public IActionResult Query([FromBody] NumberingRuleQueryParams queryParams)
        {
            try
            {
                Console.WriteLine($"【Query】用户 {GetCurrentUserName()} 执行查询");

                // 如果参数为null，创建新实例
                if (queryParams == null)
                {
                    Console.WriteLine("【Query】参数为null，使用默认参数");
                    queryParams = new NumberingRuleQueryParams();
                }

                // 确保分页参数有效
                queryParams.PageIndex = queryParams.PageIndex < 1 ? 1 : queryParams.PageIndex;
                queryParams.PageSize = queryParams.PageSize < 1 ? 10 : queryParams.PageSize;

                Console.WriteLine($"【Query】处理后的分页参数 - PageIndex: {queryParams.PageIndex}, PageSize: {queryParams.PageSize}");
                Console.WriteLine($"【Query】其他参数 - target_id: {queryParams.target_id}, number_prefix: {queryParams.number_prefix}");

                // 调用服务层获取分页结果
                var paginationResult = _numberingRuleService.GetByConditions(queryParams);

                // 确保分页结果不为null
                paginationResult ??= new PaginationResult<NumberingRule>
                {
                    Data = new List<NumberingRule>(),
                    TotalCount = 0,
                    PageIndex = queryParams.PageIndex,
                    PageSize = queryParams.PageSize
                };

                // 补充目标表单名称
                foreach (var rule in paginationResult.Data)
                {
                    rule.serial_number = rule.serial_number > 0 ? rule.serial_number : 0;
                    rule.step = rule.step > 0 ? rule.step : 1;
                    rule.time_rule = rule.time_rule ?? string.Empty;

                    if (string.IsNullOrEmpty(rule.target_form))
                    {
                        var targetForm = _targetFormService.GetById(rule.target_id);
                        rule.target_form = targetForm?.target_form ?? string.Empty;
                    }

                    if (string.IsNullOrEmpty(rule.number_production_rule))
                    {
                        rule.number_production_rule = GenerateProductionRulePreview(rule);
                    }
                }

                // 返回完整的分页信息给前端
                var result = new
                {
                    success = true,
                    data = paginationResult.Data,
                    totalCount = paginationResult.TotalCount,
                    totalPages = paginationResult.TotalPages,
                    pageIndex = paginationResult.PageIndex
                };

                Console.WriteLine($"【Query】返回结果 - PageIndex: {result.pageIndex}, TotalPages: {result.totalPages}, DataCount: {result.data.Count}");

                return Json(result);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【Query】异常：{ex.Message}\n{ex.StackTrace}");
                return Json(new { success = false, error = ex.Message });
            }
        }

        /// <summary>
        /// 显示编辑页
        /// </summary>
        public IActionResult Edit(int? rule_id)
        {
            var rule = new NumberingRule();
            try
            {
                var currentUser = GetCurrentUserName();
                ViewData["CurrentOperator"] = currentUser;
                Console.WriteLine($"【Edit】用户 {currentUser} 访问编辑页，RuleID: {rule_id}");

                if (rule_id.HasValue)
                {
                    rule = _numberingRuleService.GetById(rule_id.Value)
                          ?? throw new KeyNotFoundException("未找到指定的编号规则");
                }
                else
                {
                    return RedirectToAction("Index");
                }

                rule.step = rule.step > 0 ? rule.step : 1;
                rule.serial_number = rule.serial_number > 0 ? rule.serial_number : 3;

                var targetForms = _targetFormService.GetAll() ?? new List<TargetForm>();
                ViewBag.TargetForms = new SelectList(
                    targetForms, "target_id", "target_form", rule.target_id);

                return View(rule);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【Edit】异常：{ex.Message}\n{ex.StackTrace}");
                return View("Error", new { Message = $"加载表单失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 保存编号规则（支持新增和更新）
        /// </summary>
        [HttpPost]
        public IActionResult Save([FromBody] NumberingRule rule)
        {
            try
            {
                Console.WriteLine("==================================================");
                Console.WriteLine($"【保存操作】开始处理保存请求，时间：{DateTime.Now:yyyy-MM-dd HH:mm:ss}");

                var currentUser = GetCurrentUserName();
                Console.WriteLine($"【保存操作】当前操作人：{currentUser}");

                Console.WriteLine($"【保存操作】接收参数 - RuleID：{rule.rule_id}，TargetID：{rule.target_id}");
                Console.WriteLine($"【保存操作】完整参数：{JsonSerializer.Serialize(rule)}");

                // 参数验证
                ModelState.Remove("target_form");
                ModelState.Remove("time_rule");
                ModelState.Remove("create_by");
                ModelState.Remove("max_value");
                ModelState.Remove("last_update_time");
                ModelState.Remove("last_generation_time");

                if (string.IsNullOrWhiteSpace(rule.number_prefix))
                {
                    Console.WriteLine($"【保存操作】验证失败：编号前缀为空");
                    return Json(new { success = false, message = "编号前缀不能为空" });
                }

                if (rule.target_id <= 0)
                {
                    Console.WriteLine($"【保存操作】验证失败：目标表单ID无效");
                    return Json(new { success = false, message = "目标表单不能为空" });
                }

                if (rule.serial_number <= 0)
                {
                    Console.WriteLine($"【保存操作】验证失败：流水号位数无效");
                    return Json(new { success = false, message = "流水号位数必须大于0" });
                }

                if (rule.step <= 0)
                {
                    Console.WriteLine($"【保存操作】验证失败：步长无效");
                    return Json(new { success = false, message = "步长必须大于0" });
                }
                Console.WriteLine("【保存操作】参数验证通过");

                // 设置操作人信息
                rule.Operator = currentUser;
                rule.operator_name = currentUser; // 修复：添加operator_name字段
                rule.update_by = currentUser;
                rule.operation_time = DateTime.Now;
                rule.update_time = DateTime.Now;

                // 新增规则时设置创建人信息
                if (rule.rule_id == 0)
                {
                    rule.create_by = currentUser;
                    rule.create_time = DateTime.Now;
                    rule.is_delete = 0;
                    rule.max_value = 0;
                    Console.WriteLine($"【保存操作】新增规则，创建人：{currentUser}");
                }
                else
                {
                    Console.WriteLine($"【保存操作】更新规则，修改人：{currentUser}");
                }

                // 生成规则预览
                rule.number_production_rule = GenerateProductionRulePreview(rule);

                // 保存到数据库
                Console.WriteLine($"【保存操作】准备保存数据：{JsonSerializer.Serialize(rule)}");
                var result = _numberingRuleService.SaveRule(rule, currentUser);
                Console.WriteLine($"【保存操作】保存成功，返回RuleID：{result}");
                Console.WriteLine("==================================================\n");

                return Json(new { success = true, message = "保存成功", rule_id = result });
            }
            catch (Exception ex)
            {
                Console.WriteLine("==================================================\n");
                Console.WriteLine($"【保存操作】异常，时间：{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
                Console.WriteLine($"【保存操作】错误信息：{ex.Message}");
                Console.WriteLine($"【保存操作】堆栈跟踪：{ex.StackTrace}");
                Console.WriteLine("==================================================\n");
                return Json(new { success = false, message = $"保存失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 加载编辑/新增部分视图
        /// </summary>
        public IActionResult EditPartial(int rule_id, string target_form, string target_form_value)
        {
            try
            {
                Console.WriteLine($"【EditPartial】开始处理请求，rule_id: {rule_id}, target_form: {target_form}, target_form_value: {target_form_value}");

                var currentUser = GetCurrentUserName();
                ViewData["CurrentOperator"] = currentUser;
                Console.WriteLine($"【EditPartial】用户 {currentUser} 访问表单，RuleID: {rule_id}（0=新增）");

                NumberingRule rule;
                if (rule_id > 0)
                {
                    // 编辑：查询已有规则
                    Console.WriteLine($"【EditPartial】查询规则ID: {rule_id}");
                    rule = _numberingRuleService.GetById(rule_id);
                    if (rule == null)
                    {
                        Console.WriteLine($"【EditPartial】未找到规则ID: {rule_id}");
                        return Content("<div class='alert alert-danger'>未找到指定的编号规则</div>");
                    }
                    Console.WriteLine($"【EditPartial】找到规则: {JsonSerializer.Serialize(rule)}");
                }
                else
                {
                    // 新增：创建空规则对象，设置默认值
                    Console.WriteLine($"【EditPartial】创建新规则");
                    rule = new NumberingRule
                    {
                        step = 1,
                        serial_number = 3,
                        is_delete = 0,
                        target_id = 0
                    };
                }

                // 设置目标表单信息
                if (!string.IsNullOrEmpty(target_form))
                {
                    rule.target_form = target_form;
                }
                if (!string.IsNullOrEmpty(target_form_value) && int.TryParse(target_form_value, out int tid))
                {
                    rule.target_id = tid;
                }

                // 加载目标表单下拉列表
                Console.WriteLine($"【EditPartial】开始加载目标表单列表");
                var targetForms = _targetFormService.GetAll() ?? new List<TargetForm>();
                Console.WriteLine($"【EditPartial】获取到 {targetForms.Count} 个目标表单");

                ViewBag.TargetForms = new SelectList(targetForms, "target_id", "target_form", rule.target_id);
                Console.WriteLine($"【EditPartial】准备返回部分视图");

                return PartialView(rule);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【EditPartial】异常详情：");
                Console.WriteLine($"消息: {ex.Message}");
                Console.WriteLine($"堆栈: {ex.StackTrace}");
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"内部异常: {ex.InnerException.Message}");
                    Console.WriteLine($"内部堆栈: {ex.InnerException.StackTrace}");
                }
                return Content($"<div class='alert alert-danger'>加载表单失败: {ex.Message}</div>");
            }
        }

        /// <summary>
        /// 生成编号规则预览
        /// </summary>
        private string GenerateProductionRulePreview(NumberingRule rule)
        {
            string timePart = GenerateDatePart(rule);
            var serialPart = rule.step.ToString().PadLeft(rule.serial_number, '0');
            return $"{rule.number_prefix}{timePart}{serialPart}";
        }

        /// <summary>
        /// 导出编号规则为Excel
        /// </summary>
        public IActionResult Export(int? target_id = null, string number_prefix = "", string time_rule = "", string operation_time = "")
        {
            try
            {
                var currentUser = GetCurrentUserName();
                Console.WriteLine($"【Export】用户 {currentUser} 执行导出操作，参数：target_id={target_id}, Prefix={number_prefix}");

                var queryParams = new NumberingRuleQueryParams
                {
                    target_id = target_id,
                    number_prefix = number_prefix,
                    time_rule = time_rule,
                    operation_time = DateTime.Now,
                    PageSize = int.MaxValue,
                    PageIndex = 1
                };
                var result = _numberingRuleService.GetByConditions(queryParams);
                var rules = result?.Data ?? new List<NumberingRule>();

                foreach (var rule in rules)
                {
                    rule.serial_number = rule.serial_number > 0 ? rule.serial_number : 0;
                    rule.step = rule.step > 0 ? rule.step : 1;
                    rule.time_rule = rule.time_rule ?? string.Empty;
                    rule.number_production_rule = rule.number_production_rule ?? string.Empty;
                    rule.Operator = rule.Operator ?? "未知";

                    if (string.IsNullOrEmpty(rule.target_form))
                    {
                        var targetForm = _targetFormService.GetById(rule.target_id);
                        rule.target_form = targetForm?.target_form ?? string.Empty;
                    }
                }

                var workbook = new XSSFWorkbook();
                var sheet = workbook.CreateSheet("编号规则列表");

                var headerStyle = workbook.CreateCellStyle();
                var headerFont = workbook.CreateFont();
                headerFont.IsBold = true;
                headerStyle.SetFont(headerFont);

                var headerRow = sheet.CreateRow(0);
                string[] headers = { "规则ID", "目标表单", "编号前缀", "时间规则", "流水号位数", "步长", "生成规则预览", "操作人", "操作时间", "创建时间", "修改时间" };
                for (int i = 0; i < headers.Length; i++)
                {
                    var cell = headerRow.CreateCell(i);
                    cell.SetCellValue(headers[i]);
                    cell.CellStyle = headerStyle;
                }

                for (int i = 0; i < rules.Count; i++)
                {
                    var row = sheet.CreateRow(i + 1);
                    var rule = rules[i];

                    row.CreateCell(0).SetCellValue(rule.rule_id);
                    row.CreateCell(1).SetCellValue(rule.target_form ?? "");
                    row.CreateCell(2).SetCellValue(rule.number_prefix ?? "");
                    row.CreateCell(3).SetCellValue(rule.time_rule ?? "");
                    row.CreateCell(4).SetCellValue(rule.serial_number);
                    row.CreateCell(5).SetCellValue(rule.step);
                    row.CreateCell(6).SetCellValue(rule.number_production_rule ?? "");
                    row.CreateCell(7).SetCellValue(rule.Operator ?? "");
                    row.CreateCell(8).SetCellValue(rule.operation_time > DateTime.MinValue
                        ? rule.operation_time.ToString("yyyy-MM-dd HH:mm:ss")
                        : "-");
                    row.CreateCell(9).SetCellValue(rule.create_time.ToString("yyyy-MM-dd HH:mm:ss"));
                    row.CreateCell(10).SetCellValue(rule.update_time.ToString("yyyy-MM-dd HH:mm:ss"));
                }

                for (int i = 0; i < headers.Length; i++)
                {
                    sheet.AutoSizeColumn(i);
                }

                using (var memoryStream = new MemoryStream())
                {
                    workbook.Write(memoryStream);
                    var byteArray = memoryStream.ToArray();
                    return File(
                        byteArray,
                        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                        $"编号规则列表_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
                    );
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【Export】异常：{ex.Message}\n{ex.StackTrace}");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取最大流水号
        /// </summary>
        [HttpGet]
        public IActionResult GetMaxSerialNumberByRuleId(int rule_id)
        {
            try
            {
                Console.WriteLine($"【GetMaxSerialNumber】用户 {GetCurrentUserName()} 查询规则 {rule_id} 的最大流水号");

                if (rule_id <= 0)
                {
                    return Json(new { success = false, message = "规则ID必须大于0" });
                }

                var rule = _numberingRuleService.GetById(rule_id);
                if (rule == null)
                {
                    return Json(new { success = false, message = $"未找到ID为{rule_id}的编号规则" });
                }

                return Json(new
                {
                    success = true,
                    maxSerialNumber = rule.max_value,
                    message = "获取最大流水号成功"
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【GetMaxSerialNumber】异常：{ex.Message}\n{ex.StackTrace}");
                return Json(new { success = false, message = $"获取失败：{ex.Message}" });
            }
        }

        /// <summary>
        /// 显示新增编号规则页面
        /// </summary>
        public IActionResult Add()
        {
            try
            {
                var currentUser = GetCurrentUserName();
                ViewData["CurrentOperator"] = currentUser;
                Console.WriteLine($"【Add】用户 {currentUser} 访问新增编号规则页面");

                var targetForms = _targetFormService.GetAll() ?? new List<TargetForm>();
                ViewBag.TargetForms = targetForms.Select(f => new SelectListItem
                {
                    Value = f.target_id.ToString(),
                    Text = f.target_form
                }).ToList();

                return View();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【Add】异常：{ex.Message}\n{ex.StackTrace}");
                return View("Error", new { Message = $"加载新增页面失败: {ex.Message}" });
            }
        }

        public class AddBothModel
        {
            public string target_form_name { get; set; }
            public string target_name { get; set; }
            public string rule_prefix { get; set; }
            public int serial_number_length { get; set; }
            public int step { get; set; }
            public string production_rule { get; set; }
            public string time_rule { get; set; }
        }

        /// <summary>
        /// 同时添加目标表单和编号规则 - 修复版本
        /// </summary>
        [HttpPost]
        public IActionResult AddBoth([FromBody] AddBothModel model)
        {
            try
            {
                Console.WriteLine("【AddBoth】开始处理请求");
                Console.WriteLine($"【AddBoth】接收参数：target_form_name={model.target_form_name}, rule_prefix={model.rule_prefix}, time_rule={model.time_rule}");

                // 基础验证
                if (string.IsNullOrWhiteSpace(model.target_form_name))
                {
                    return Json(new { success = false, message = "目标表单名称不能为空" });
                }
                if (string.IsNullOrWhiteSpace(model.rule_prefix))
                {
                    return Json(new { success = false, message = "编号前缀不能为空" });
                }

                // 目标表单名称唯一性校验
                string targetFormName = model.target_form_name.Trim();
                bool formExists = _targetFormService.ExistsByFormName(targetFormName);
                if (formExists)
                {
                    Console.WriteLine($"【AddBoth】校验失败：目标表单名称 '{targetFormName}' 已存在");
                    return Json(new { success = false, message = $"目标表单名称 '{targetFormName}' 已存在，请更换" });
                }

                // 构建实体
                var targetForm = new TargetForm
                {
                    target_form = targetFormName,
                    is_active = 1,
                    creation_time = DateTime.Now
                };

                var numberingRule = new NumberingRule
                {
                    target_id = 0, // 会在Repository中设置
                    number_prefix = model.rule_prefix.Trim(),
                    serial_number = model.serial_number_length > 0 ? model.serial_number_length : 3,
                    step = model.step > 0 ? model.step : 1,
                    number_production_rule = model.production_rule,
                    time_rule = model.time_rule ?? "YYYYMMDD",
                    operator_name = GetCurrentUserName(),
                    Operator = GetCurrentUserName(),
                    operation_time = DateTime.Now,
                    create_by = GetCurrentUserName(),
                    create_time = DateTime.Now,
                    is_delete = 0,
                    max_value = 0
                };

                // 执行添加操作
                Console.WriteLine($"【AddBoth】准备调用 AddTargetAndRule");
                var currentUser = GetCurrentUserName();
                int newRuleId = _numberingRuleService.AddTargetAndRule(targetForm, numberingRule, currentUser);
                Console.WriteLine($"【AddBoth】添加成功，返回RuleID：{newRuleId}");

                return Json(new { success = true, rule_id = newRuleId, message = "添加成功" });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【AddBoth】异常：{ex.Message}");
                Console.WriteLine($"【AddBoth】堆栈跟踪：{ex.StackTrace}");
                return Json(new { success = false, message = $"添加失败：{ex.Message}" });
            }
        }

        // 删除请求模型
        public class DeleteRuleRequest
        {
            public int rule_id { get; set; }
        }

        /// <summary>
        /// 删除编号规则
        /// </summary>
        [HttpPost]
        public IActionResult Delete([FromBody] DeleteRuleRequest request)
        {
            try
            {
                Console.WriteLine($"【Delete】用户 {GetCurrentUserName()} 尝试删除规则ID: {request.rule_id}");

                if (request.rule_id <= 0)
                {
                    Console.WriteLine($"【Delete】错误：规则ID必须大于0，收到：{request.rule_id}");
                    return Json(new { success = false, message = "规则ID必须大于0" });
                }

                var currentUser = GetCurrentUserName();
                bool result = _numberingRuleService.DeleteRule(request.rule_id, currentUser);

                if (result)
                {
                    Console.WriteLine($"【Delete】规则ID: {request.rule_id} 删除成功");
                    return Json(new { success = true, message = "删除成功" });
                }
                else
                {
                    Console.WriteLine($"【Delete】规则ID: {request.rule_id} 删除失败，未找到该规则或已被删除");
                    return Json(new { success = false, message = "删除失败，未找到该规则或已被删除" });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【Delete】异常: {ex.Message}\n{ex.StackTrace}");
                return Json(new { success = false, message = $"删除失败: {ex.Message}" });
            }
        }

        /// <summary>
        /// 校验目标表单名称是否已存在
        /// </summary>
        [HttpGet]
        public IActionResult CheckTargetFormExists(string target_form_name)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(target_form_name))
                {
                    return Json(new { exists = false, message = "表单名称不能为空" });
                }

                bool exists = _targetFormService.ExistsByFormName(target_form_name.Trim());
                return Json(new
                {
                    exists = exists,
                    message = exists ? "该表单名称已存在，请更换" : "表单名称可用"
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"【CheckTargetFormExists】异常：{ex.Message}");
                return Json(new { exists = false, message = "校验失败，请重试" });
            }
        }
    }
}